import * as express from "express";
import * as path from "path";
import {User} from '../models/User';
import {AuthenticateUser} from '../models/AuthenticateUser';
import {BaseController} from './BaseController';
import {UserRegisterDto} from '../dtos/users/UserRegisterDto';
import {UserLoginedDto} from '../dtos/users/return/UserLoginedDto';
import {UserUpdateDto} from '../dtos/users/UserUpdateDto';
import {UsersService} from '../services/UsersService';
export class UserController extends BaseController
{
  usersService:UsersService;
  constructor(app:express.Application){
    super(app);
    var $this = this;
    app.get(this.domain+"/users/login",(req,res)=>{
      $this.handerErr(req,res,()=>{
        $this.login(req,res);
      })
    });
    app.post(this.domain+"/users/register",(req,res)=>{
      $this.handerErr(req,res,()=>{
        $this.register(req,res);
      })
    });
    app.put(this.domain+"/users",(req,res)=>{
      $this.handerErr(req,res,(user:User)=>{
        $this.updateUserInfo(req,res,user);
      },true);
    });
    this.usersService = new UsersService();
  }

  login(req: express.Request, res: express.Response){
    super.initResponse(res);
    var username = req.header("x-username");
    var password = req.header("x-password");
    this.usersService.login(username,password,(err,authUser:AuthenticateUser)=>{
      if(!err && authUser)
      {
        var userLoginedDto:UserLoginedDto = new UserLoginedDto(authUser);
        res.send(JSON.stringify(userLoginedDto));
      }else
      {
        res.status(404);
        res.send({msg:"error!"});
      }
    })

  }

  register(req: express.Request, res: express.Response){
    super.initResponse(res);
    this.usersService.register(UserRegisterDto.toUser(req.body),(err,user:User)=>{
      user.password = undefined;
      res.send(JSON.stringify(user));
    });
  }

  updateUserInfo(req: express.Request, res: express.Response,user:User)
  {
    //success
    var userId =  user._id;
    var user:User = UserUpdateDto.toUser(userId,req.body);
    this.usersService.update(user,(err,user)=>{
      res.send(JSON.stringify(user));
    })
  }

}
